'''
Created on 2020年3月3日

@author: Administrator
'''
import datetime
from flask import json

from common.public import *
from orm.model import Dept, User, UserApp,Position, db, PositionApp, AllApp
from view.aouthview import AouthView
from view.baseview import BaseView


class UserView(BaseView):
    def __init__(self):
        pass
    def login(self,username,password):
#         try:
        user = User.select().where(((User.username==username) | (User.phone==username))
               & (User.password == password)).first()
        if user:
            if not user.isactive==COMMON_TRUE:
                return super().resultSet(402, "账号已禁用，请与管理员联系！", {"userid":user.id,"username":user.username,"token":""})
            return super().resultSet(200, "授权成功！", {"userid":user.id, "username":user.username, "ismanager":user.ismanager, "isleader":user.isleader, "deptid":user.dept_id, "deptname":user.dept.name, "token":AouthView().generate_token()})
#         except:
        return super().resultSet(401, "授权失败，请重新登录！", {"userid":"","username":"","token":""})

    def getUserApp(self, userid):
        """取得用户应用列表 id：用户ID"""
        data = []
        user = User.select().where(User.id==userid);
        apps = PositionApp.select().where(PositionApp.position_id==user[0].position_id).order_by(PositionApp.app_id.asc())
        # apps = UserApp.select().where(UserApp.user_id==userid).order_by(UserApp.app_id.asc())
        for app in apps:
            data.append({"id":app.id,"path":app.app_id.path + "?timelamp=" + str(datetime.datetime.now()),"imgsrc":app.app_id.imgsrc,"text":app.app_id.text,"groupid":app.app_id.group_id.id,"group":app.app_id.group_id.groupname})
        return super().resultSet(200, "应用列表取得成功！",  data)
    def getPhoneApps(self, userid):
        """取得用户手机应用列表 id：用户ID"""
        data = []
        userapps = UserApp.select().where((UserApp.user_id==userid)).order_by(UserApp.app_id.asc())
        for app in userapps:
            if (app.app_id.group_id.id == APP_GROUP_PHONE):
                spitems = app.app_id.imgsrc.split("/")
                lastitem = spitems[len(spitems)-1]
                icon = lastitem.split(".")[0]
                data.append({"id":app.id,"path":app.app_id.path + "?timelamp=" + str(datetime.datetime.now()),"icon":icon,"text":app.app_id.text})
        return super().resultSet(200, "应用列表取得成功！",  data)

    def getAllUsers(self,):
        """取得用户列表"""
        result=[]
        rows = User.select().where(User.isactive==COMMON_TRUE).order_by(User.dept.desc())
        for row in rows:
            data = {
                "id":row.id,
                "name":row.username,
               }
            result.append(data )
        return super().resultSet(200, "用户列表取得成功", result)

    def getAccountant(self,):
        """取得会计列表"""
        result = []
        whereCondtion = True
        rows = User.select().where((User.isactive == COMMON_TRUE) & whereCondtion).order_by(User.dept.desc(), User.leader_id.desc(), User.id.desc())
        dname = ""
        for row in rows:
            if dname != row.dept.name:
                group = {"deptname":row.dept.name, "users":[]}
                result.append(group)
                dname = row.dept.name
            else:
                continue
        for row in rows:
            for group in result:
                data = {
                    "id":row.id,
                    "name":row.username,
                   }
                if group["deptname"] == row.dept.name:
                    group["users"].append(data)
                else:
                    continue
        return super().resultSet(200, "用户列表取得成功", result)
    def getUsers(self,params):
        """根据部门，团队取得用户列表"""
        result=[]
        whereCondtion = True
        if ('dept' in params) and params['dept']:
            whereCondtion = whereCondtion & (User.dept.in_(params['dept']))
        if ('team' in params) and params['team']:
            whereCondtion = whereCondtion & (User.leader_id.in_(params['team']))
        rows = User.select().where((User.isactive==COMMON_TRUE) & whereCondtion).order_by(User.dept.desc(),User.leader_id.desc(),User.id.desc())
        dname = ""
        for row in rows:
            if dname!=row.dept.name:
                group = {"deptname":row.dept.name,"users":[]}
                result.append(group)
                dname = row.dept.name
            else:
                continue
        for row in rows:
            for group in result:
                data = {
                    "id":row.id,
                    "name":row.username,
                   }
                if group["deptname"]==row.dept.name:
                    group["users"].append(data)
                else:
                    continue
        return super().resultSet(200, "用户列表取得成功", result)

    def getAllLeader(self,):
        """取得主管列表"""
        result=[]
        rows = User.select().where((User.isactive==COMMON_TRUE) & (User.isleader == COMMON_TRUE)).order_by(User.dept.desc())
        dname = ""
        for row in rows:
            if dname!=row.dept.name:
                group = {"deptname":row.dept.name,"users":[]}
                result.append(group)
                dname = row.dept.name
            else:
                continue
        for row in rows:
            for group in result:
                data = {
                    "id":row.id,
                    "name":row.username,
                   }
                if group["deptname"]==row.dept.name:
                    group["users"].append(data)
                else:
                    continue
        return super().resultSet(200, "主管列表取得成功", result)

    def getLeader(self, dept_ids):  # dept_ids = []
        """根据部门取得主管列表"""
        # print(dept_ids)
        # dept_ids = []
        result=[]
        if dept_ids:
            rows = User.select().where((User.isactive==COMMON_TRUE) & (User.isleader == COMMON_TRUE) & (User.dept_id.in_(dept_ids))).order_by(User.dept.desc())
        else:
            return super().resultSet(200, "主管列表为空", result)
        dname = ""
        for row in rows:
            if dname!=row.dept.name:
                group = {"deptname":row.dept.name,"users":[]}
                result.append(group)
                dname = row.dept.name
            else:
                continue
        for row in rows:
            for group in result:
                data = {
                    "id":row.id,
                    "name":row.username,
                   }
                if group["deptname"]==row.dept.name:
                    group["users"].append(data)
                else:
                    continue
        return super().resultSet(200, "主管列表取得成功", result)

    def getUserLeader(self, params):
        """根据部门取得主管列表"""
        result = []
        if params["deptid"]:
            rows = User.select().where((User.isactive == COMMON_TRUE) & (User.isleader == COMMON_TRUE) & (User.dept_id == params["deptid"])).order_by(User.dept.desc())
        else:
            return super().resultSet(200, "主管为空", result)
        for row in rows:
            data = {
                "id":row.id,
                "username":row.username,
              "isactive":row.isactive,
              "ismanager":row.ismanager,
              "isleader":row.isleader,
              "leaderid":row.leader_id,
               }
            result.append(data)
        return super().resultSet(200, "主管列表取得成功", result)

    def queryUsers(self, params):
        """根据条件取得用户信息，params：条件参数"""
        # print(params)
        result=[]
        where_condition = True
        if params["username"]:
            likestr= "%"+params["username"] +"%"
            where_condition=(User.username** likestr )
        if params["sex"]:
            likestr= "%"+params["sex"] +"%"
            where_condition=where_condition & (User.sex** likestr )
        # positionid
        if params["positionid"]:
            likestr = "%" + str(params["positionid"]) + "%"
            where_condition = where_condition & (User.position_id ** likestr)
        if params["address"]:
            likestr= "%"+params["address"] +"%"
            where_condition=where_condition &(User.address ** likestr )
        if params["phone"]:
            likestr= "%"+params["phone"] +"%"
            where_condition=where_condition &(User.phone ** likestr )
        if params["isactive"]:
            likestr= params["isactive"]
            where_condition=where_condition &(User.isactive ==likestr )
        if params["deptid"] > 0:
            if params["type"] == COMMON_DEPT:
                #部门
                subdeptids = Dept.select(Dept.id).where(Dept.up_id==params["deptid"])
                if subdeptids:
                    # 有子部门
                    if 1==params["deptid"]:
                        where_condition=where_condition &(User.dept_id ==params["deptid"])
                    else:
                        where_condition=where_condition &(User.dept.in_(subdeptids))
                else:
                    # 无子部门
                    where_condition=where_condition &(User.dept_id ==params["deptid"])
            else:
                #团队
                where_condition=where_condition &(User.leader_id ==params["deptid"] )
        total = User.select().where(where_condition).count()
        rows = User.select().where(where_condition).order_by(User.dept.desc(),User.username.desc()).paginate(int(params["pageNo"]), int(params["pagesize"]))
        for row in rows:
            # print("标记-1",row.userapp_set)
            defaultapps = []
            desktopapps = []
            phoneapps = []
            positionapps = PositionApp.select().where(PositionApp.position_id == row.position_id).order_by(PositionApp.app_id.asc())
            for positionapp in positionapps:
                allapp = AllApp.select().where(AllApp.id == positionapp.app_id)
                if allapp[0].group_id.id == 1:
                    defaultapps.append(positionapp.app_id.id)
                elif allapp[0].group_id.id ==2:
                    desktopapps.append(positionapp.app_id.id)
                elif allapp[0].group_id.id ==4:
                    phoneapps.append(positionapp.app_id.id)
                else:
                    pass
            position = ""
            if row.position_id !=0:
                position = row.position.name
            data = {
                "id":row.id,
                "username":row.username,
                "password":row.password,
                "repassword":row.password,
               "sex":row.sex,
               "address":row.address,
               "dept_id":row.dept.id,
               "dept":row.dept.name,
                "positionid": row.position_id,
               "position":position,
               "phone":row.phone,
                "birthday":str(row.birthday),
                "idcards":json.loads(row.idcards),
              "isactive":row.isactive,
              "ismanager":row.ismanager,
              "isleader":row.isleader,
              "leaderid":row.leader_id,
              "employdate":str(row.employdate),
              "leavedate":str(row.leavedate),
               "status":str(row.status),
               "workstatus":str(row.workstatus),
               "workplace":str(row.workplace),
             "defaultapps":defaultapps,
              "desktopapps":desktopapps,
              "phoneapps":phoneapps,
               }
            result.append(data)
            # print(1,data)
        # print(2,result)
        return super().resultSet(200, "", result,total=total)

    def queryDeptUsers(self, params):
        """根据条件取得用户信息，params：条件参数"""
        # print(params)
        result = []
        result_condition = []
        where_condition = True
        if params["ids"]:
            for id in params["ids"]:
                where_condition = True
                where_condition = where_condition & (User.status == USER_STATUS_ON)
                # 取得id对应索引（如果id不唯一可能重复不可用。两个id相同时返回的索引只为第一个）
                indextype = params["ids"].index(id)
                if params["persontype"][indextype] == COMMON_DEPT:
                    # 部门
                    subdeptids = Dept.select(Dept.id).where(Dept.up_id == id)
                    if subdeptids:
                        # 有子部门
                        if 1 == id:
                            where_condition = where_condition & (User.dept_id == id)
                        else:
                            where_condition = where_condition & (User.dept.in_(subdeptids))
                    else:
                        # 无子部门
                        where_condition = where_condition & (User.dept_id == id)
                else:
                    # 团队
                    where_condition = where_condition & (User.leader_id == id)
                result_condition.append(where_condition)

        total = 0
        rows = User.select(User.username, User.dept_id).where(1 == 2)
        if result_condition != []:
            for where_condition in result_condition:
                rows1 = User.select(User.username, User.dept_id).where(where_condition)
                rows = rows.union(rows1)
            total = rows.count()
            rows = rows.order_by(User.dept.desc(), User.username.desc())
        for row in rows:
            data = {
                "id":row.id,
                "username":row.username,
                "password":row.password,
                "repassword":row.password,
               "sex":row.sex,
               "address":row.address,
               "dept_id":row.dept.id,
               "dept":row.dept.name,
               "phone":row.phone,
              "isactive":row.isactive,
              "ismanager":row.ismanager,
              "isleader":row.isleader,
              "leaderid":row.leader_id,

               }
            result.append(data)
        return super().resultSet(200, "", result, total = total)
    def checkNameDistinct(self, params):
        """
        检查用户名和电话号码有没有重复
        """
        checkPass = super().resultSet(200, "姓名检查通过", {})
        usernameNopass = super().resultSet(420, "姓名不能重复。", {})
        userfind = User.select().where(User.username==params["username"]).first()
        if userfind:
            if userfind.id == params["id"]:
                return checkPass
            else:
                return usernameNopass
        return checkPass

    def checkPhoneDistinct(self, params):
        """
        检查用户名和电话号码有没有重复
        """
        checkPass = super().resultSet(200, "检查电话号码通过", {})
        phoneNopass = super().resultSet(420, "电话不能重复。", {})
        phonfind = User.select().where(User.phone==params["phone"]).first()
        if phonfind:
            if phonfind.id == params["id"]:
                return checkPass
            else:
                return phoneNopass
        else:
            return checkPass

    @db.atomic()
    def updateUser(self, params):
        """
        更新用户
        """
        checkname = self.checkNameDistinct(params)
        checkphone = self.checkPhoneDistinct(params)
        if checkname["code"] == 200:
            if checkphone["code"] == 200:
                user = User.get(User.id==params["id"])
                user.username =params["username"]
                user.sex =params["sex"]
                user.birthday =params["birthday"]
                user.address =params["address"]
                user.phone =params["phone"]
                user.dept_id =params["dept_id"]
                user.position_id = params["positionid"]
                user.isactive =params["isactive"]
                user.isleader =params["isleader"]
                user.ismanager =params["ismanager"]
                user.leader_id =params["leaderid"]
                user.password =params["password"]
                user.employdate=params["employdate"]
                user.leavedate=params["leavedate"]
                user.status=params["status"]
                user.workstatus=params["workstatus"]
                user.workplace=params["workplace"]
                user.idcards =json.dumps(params["idcards"])
                user.save()
                user.desktopapps = params["desktopapps"]
                # 清空用户应用列表
                # res = UserApp.delete().where(UserApp.user_id ==params["id"]).execute()
                # # 添加用户应用列表
                # for appid in params["defaultapps"]:
                #     UserApp.create(user_id=params["id"],app_id=appid)
                # for appid in params["desktopapps"]:
                #     UserApp.create(user_id=params["id"],app_id=appid)
                # for appid in params["phoneapps"]:
                #     UserApp.create(user_id=params["id"],app_id=appid)
                position = ""
                if user.position_id !=0:
                    position = user.position.name
                data = {
                    "id":user.id,
                    "username":user.username,
                    "password":user.password,
                    "repassword":user.password,
                       "sex":user.sex,
                       "address":user.address,
                       "phone":user.phone,
                       "dept_id":user.dept.id,
                       "dept":user.dept.name,
                       "positionid": user.position_id,
                       "position":position,
                        "birthday":str(user.birthday),
                       "idcards":json.loads(user.idcards),
                      "defaultapps":params["defaultapps"],
                      "desktopapps":params["desktopapps"],
                      "phoneapps":params["phoneapps"],
                      "ismanager":user.ismanager,
                       "isleader":user.isleader,
                       "leaderid":user.leader_id,
                       "employdate":str(user.employdate),
                      "leavedate":str(user.leavedate),
                       "status":str(user.status),
                       "workstatus":str(user.workstatus),
                       "workplace":str(user.workplace),
                      "isactive":user.isactive
                       }
                return super().resultSet(200, "用户更新成功", data)
            else:
                return checkphone
        else:
            return checkname
        raise Exception("用户更新失败")

    @db.atomic()
    def addUser(self, params):
        """
        添加用户
        """
        # print('position: ',params['position'])
        # print('phoneapps: ',params['phoneapps'])
        checkname = self.checkNameDistinct(params)
        checkphone = self.checkPhoneDistinct(params)
        if checkname["code"] == 200:
            if checkphone["code"] == 200:
                user = User.create(
                    username=params["username"],
                    password = params["password"],
                    isactive=params["isactive"],
                    ismanager=params["ismanager"],
                    isleader=params["isleader"],
                    leader_id = params["leaderid"],
                    position_id = params["positionid"],
                    sex= params["sex"],
                    birthday=params["birthday"],
                    address=params["address"],
                    phone=params["phone"],
                    dept_id=params["dept_id"],
                    employdate=params["employdate"],
                    leavedate=params["leavedate"],
                    status=params["status"],
                    workstatus=params["workstatus"],
                    workplace=params["workplace"],
                    idcards=json.dumps(params["idcards"]))
                # 添加用户应用列表
                for appid in params["defaultapps"]:
                    UserApp.create(user_id=user,app_id=appid)
                for appid in params["desktopapps"]:
                    UserApp.create(user_id=user,app_id=appid)
                # for appid in params["phoneapps"]:
                #     UserApp.create(user_id=user,app_id=appid)
                print(user.position_id)
                # print(user.position.name)
                position = ""
                if user.position_id !=0:
                    position = (Position.select().where(Position.id==user.position_id))[0].name
                data = {
                    "id":user.id,
                    "username":user.username,
                    "password":user.password,
                    "repassword":user.password,
                       "sex":user.sex,
                       "address":user.address,
                       "phone":user.phone,
                        "birthday":str(user.birthday),
                        "dept_id":user.dept.id,
                        "dept":user.dept.name,
                        "positionid": user.position_id,
                        "position":position,
                       "idcards":json.loads(user.idcards),
                      "defaultapps":params["defaultapps"],
                      "desktopapps":params["desktopapps"],
                      "phoneapps":"",
                      "ismanager":user.ismanager,
                      "isleader":user.isleader,
                      "leaderid":user.leader_id,
                      "employdate":str(user.employdate),
                      "leavedate":str(user.leavedate),
                       "status":str(user.status),
                       "workstatus":str(user.workstatus),
                       "workplace":str(user.workplace),
                      "isactive":user.isactive
                       }
                return super().resultSet(200, "用户插入成功", data)
            else:
                return checkphone
        else:
            return checkname
        raise Exception("用户添加失败")
        
    @db.atomic()
    def deleteUser(self, userids):
        """
        删除用户
        """
        print(params)
        userdel = User.delete().where(User.id.in_(userids)).execute()
        appdel = UserApp.delete().where(UserApp.user_id.in_(userids)).execute()
        if userdel>=0 and appdel>=0:
            return super().resultSet(200, "删除成功", {})
        return super().resultSet(403, "删除失败", {})
        raise Exception("用户删除失败")
    @db.atomic()                   
    def updateUserPassword(self, params):
        """
        更新用户
        """
        print(params)
        user = User.get(User.id==params["userid"])
        user.password =params["Password"]
        user.save()      
        data = {
            "id":user.id,
            "password":user.password,
               }
        return super().resultSet(200, "用户更新成功", data)
        raise Exception("用户更新失败")

    @db.atomic()                   
    def addDeptGroup(self, params):
        """
        更新用户
        """
        print(params)
        dept = Dept.create(
            name=params["deptname"],
            up_id = params["region"],
            type="部门"
            )
             
        
        return super().resultSet(200, "用户更新成功",[])
        raise Exception("用户更新失败")
    
    @db.atomic()
    def removeUserDept(self, params):
        """
        删除用户
        """
        print(params)
        deptdel = Dept.delete().where(Dept.id==params["deptid"]).execute()

        return super().resultSet(200, "删除成功", {})
        raise Exception("用户删除失败")
if __name__ == '__main__':
    view = UserView()
    params = {"dept":[2],"team":[5]}
    personnel = view.getUsers(params)
    print(personnel)
